package com.zhangyan.exception;

import com.zhangyan.common.BaseResponse;
import com.zhangyan.common.ErrorCode;
import com.zhangyan.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * 全局异常处理器
 * @author zhangyan
 */

@Slf4j
@RestControllerAdvice  //捕获整个应用程序中所有控制器抛出的异常，并返回统一格式的响应。
public class GlobalExceptionHandler {


    @ExceptionHandler(BusinessException.class) //只捕获BusinessException一个异常
    public BaseResponse businessExceptionHandler(BusinessException e) {
        log.error("BusinessException" + e.getMessage(), e);
        return ResultUtils.error(e.getCode(),e.getMessage(),e.getDescription());
    }

    @ExceptionHandler(RuntimeException.class) //只捕获BusinessException一个异常
    public BaseResponse runtimeExceptionHandler(BusinessException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage(), "");
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public BaseResponse handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage(), "上传的文件异常,请检查");
    }
}
